package com.mxm.mall.demo.math;


import com.mxm.mall.demo.entity.FullReduction;
import com.mxm.mall.demo.entity.Product;
import com.mxm.mall.demo.entity.ShoopingCar;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * 价格计算
 *
 * @author mxm
 */
public class ProductMath {


    /**
     * 计算商品总额
     *
     * @param shoopingCars
     * @param productMap
     * @return
     */
    private static BigDecimal mathSum(List<ShoopingCar> shoopingCars, Map<Integer, Product> productMap) {
        BigDecimal sum = BigDecimal.ZERO;
        for (ShoopingCar shoopingCar : shoopingCars) {
            Product product = productMap.get(shoopingCar.getProductId());
            if (product == null) {
                throw new RuntimeException("商品不存在！");
            }
            sum = sum.add(shoopingCar.getAmount().multiply(product.getPrice()).multiply(product.getDiscount()));
        }
        return sum;
    }


    /**
     * 计算满减
     *
     * @param sum
     * @param fullReduction
     * @return
     */
    private static BigDecimal mathFullReduction(BigDecimal sum, FullReduction fullReduction) {

        BigDecimal cnt = sum.divide(fullReduction.getFull(), 0, RoundingMode.DOWN);


        return sum.subtract(cnt.multiply(fullReduction.getReduction()));
    }


    /**
     * 计算商品总额
     *
     * @param shoopingCars  购买的商品列表
     * @param productMap    产品价格列表
     * @param fullReduction 满减优惠
     * @return
     */
    public static BigDecimal match(List<ShoopingCar> shoopingCars, Map<Integer, Product> productMap, FullReduction fullReduction) {

        // 计算总额
        BigDecimal sum = mathSum(shoopingCars, productMap);

        //如果有满减计算满减
        if (fullReduction != null) {
            sum = mathFullReduction(sum, fullReduction);
        }

        return sum.setScale(2, RoundingMode.HALF_DOWN);
    }

}
